package com.x.Part6_死锁和JUC的Lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ClassName: LockTest
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.03.27 22:56
 */


public class LockTest {
    public static void main(String[] args) {

        Window window = new Window();

        new Thread(window).start();
        new Thread(window).start();
        new Thread(window).start();
    }
}

class Window implements Runnable{
    int ticket = 100000;

    //1、创建lock实例，确保多个线程使用同一个lock，需要考虑声明为static final
    private static final ReentrantLock lock = new ReentrantLock();//全局唯一


    @Override
    public void run() {
        while (true){

            try {
                //2、加锁：共享资源开始
                lock.lock();

                if(ticket>0){
                    System.out.println(Thread.currentThread().getName()+"票号为：" + ticket);
                    ticket--;
                }else
                    break;
            } finally {
                //3、解锁：共享资源结束
                //4、保证unlock执行，防止break后不unlock，放入finally中
                lock.unlock();
            }
        }
    }
}

